import type { RouteRecordRaw } from "vue-router";
import type { DeptDetailResult, TokenResult, UserResult } from "@/api/types";
import type { MultiTag } from "@/stores/multiTags";
import { StorageSerializers, useStorage } from "@vueuse/core";

/**
 * Note[vueuse]
 * useStorage第二个参数传null表示默认初始化为无
 * 第二个参数传null时, useStorage无法从中假定数据类型, 参考: https://vueuse.nodejs.cn/core/useStorage/#custom-serialization
 * 同时第二个参数传null, 但是useStorage返回的类型并不包含null, 需要手动添加上null, 除非确认后续使用都不会为null
 *
 * Note[vueuse]: 当你提供 null 作为默认值时, useStorage 无法从中假定数据类型, 参考: https://vueuse.nodejs.cn/core/useStorage/#custom-serialization
 */

/** 存储全局配置 */
export const platformConfigKey = "__platform_configs";
export const platformConfigsStorage = useStorage<PlatformConfigs | null>(
    platformConfigKey,
    null,
    localStorage,
    { serializer: StorageSerializers.object },
);

/** 存储用户信息 */
export const userKey = "__user_info";
export const userStorage = useStorage<UserResult | null>(
    userKey,
    null,
    localStorage,
    { serializer: StorageSerializers.object },
);

/** 存储用户部门信息 */
export const userDeptKey = "__user_dept";
export const userDeptStorage = useStorage<DeptDetailResult | null>(
    userDeptKey,
    null,
    localStorage,
    { serializer: StorageSerializers.object },
);

/** 存储用户的`token`信息 */
export const tokenKey = "__authorized_token";
export const tokenStorage = useStorage<TokenResult | null>(
    tokenKey,
    null,
    localStorage,
    { serializer: StorageSerializers.object },
);

/** 存储后端权限 */
export const asyncPermissionKey = "__async_permission";
export const asyncPermissionStorage = useStorage<{
    routes: RouteRecordRaw[];
    permissions: string[];
} | null>(
    asyncPermissionKey,
    null,
    localStorage,
    { serializer: StorageSerializers.object },
);

/** 存储菜单搜索历史 */
export const menuHistoryKey = "__menu_search_history";
export const menuHistoryStorage = useStorage<RouteRecordRaw[] | null>(
    menuHistoryKey,
    null,
    localStorage,
    {
        serializer: StorageSerializers.object,
        mergeDefaults: storageValue => storageValue, // 直接使用传入的值
    },
);

/** 存储菜单收藏 */
export const menuCollectKey = "__menu_search_collect";
export const menuCollectStorage = useStorage<RouteRecordRaw[] | null>(
    menuCollectKey,
    null,
    localStorage,
    {
        serializer: StorageSerializers.object,
        mergeDefaults: storageValue => storageValue,
    },
);

/** 存储页签 */
export const multiTagsKey = "__multi_tags";
export const multiTagsStorage = useStorage<MultiTag[] | null>(
    multiTagsKey,
    null,
    localStorage,
    {
        serializer: StorageSerializers.object,
        mergeDefaults: storageValue => storageValue,
    },
);
